package com.usts2022.classcostrecord;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;

import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.usts2022.classcostrecord.Utils.HttpUtils;
import com.usts2022.classcostrecord.entity.Report;
import com.usts2022.classcostrecord.entity.User;
import com.usts2022.classcostrecord.entity.UserViewModel;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private FragmentManager fragmentManager;
    private static final String TAG = "MainActivity";
    private RadioGroup rg_main;
    private RadioButton rbAdd;
    private UserViewModel userViewModel;
    private static final Integer LIST_FRAGMENT = 1;
    private static final Integer ME_FRAGMENT = 2;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //刷新登录事件
        if (requestCode == MeFragment.LOGIN_CODE && resultCode == LoginFragment.LOGIN_RESULT_CODE) {
            String[] strings = dataLoad();
            try {
                isLogin(strings[0], strings[1], ME_FRAGMENT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //创建ViewModel
        userViewModel = new ViewModelProvider(MainActivity.this).get(UserViewModel.class);
        String[] dataLoad = dataLoad();
        try {
            isLogin(dataLoad[0], dataLoad[1], LIST_FRAGMENT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        fragmentManager = getSupportFragmentManager();
        //绑定
        rbAdd = findViewById(R.id.rb_add);

        //底栏
        rg_main = findViewById(R.id.rg_main);
        rg_main.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int i = 0; i < rg_main.getChildCount(); i++) {
                    RadioButton rb = (RadioButton) group.getChildAt(i);
                    if (rb.isChecked()) {
//                        Log.d(TAG, "onCheckedChanged: " + i);
                        setIndexSelectedTwo(i);
                        break;
                    }
                }
            }
        });

    }


    //菜单方法
    public void setIndexSelectedTwo(int i) {
        switch (i) {
            case 0:
                ListFragment listFragment = new ListFragment();
                fragmentManager.beginTransaction().replace(R.id.fragment, listFragment).commitAllowingStateLoss();
                break;
            case 1:
                AddFragment addFragment = new AddFragment();
                fragmentManager.beginTransaction().replace(R.id.fragment, addFragment).commitAllowingStateLoss();
                break;
            case 2:
                MeFragment meFragment = new MeFragment();
                fragmentManager.beginTransaction().replace(R.id.fragment, meFragment).commitAllowingStateLoss();
                break;
        }
    }


    //检验登录信息
    public void isLogin(String account, String password, Integer flag) throws IOException {
        String url = "/user/login/" + account + "/" + password;
        HttpUtils.get(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (Looper.myLooper() == null)
                    Looper.prepare();
                String str = response.body().string();
                if (response.code() != 200 || str.equals("")) {
                    Toast.makeText(MainActivity.this, "请登录", Toast.LENGTH_SHORT).show();
                } else {
                    User user = JSON.parseObject(str, User.class);
                    userViewModel.setUser(user);
                    //判断是否为记录员
                    if (userViewModel.getUser().getIsReporter() == 1) {
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                rbAdd.setVisibility(View.VISIBLE);
                            }
                        });
                    }else if (userViewModel.getUser().getIsReporter() == 0) {
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                rbAdd.setVisibility(View.GONE);
                            }
                        });
                    }
                    getReport(user.getClassCode(), flag);
                }
                Looper.loop();
            }
        });
    }

    private void getReport(Integer classCode, Integer flag) throws IOException {
        String url = "/user/getReports/" + classCode;
        HttpUtils.get(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (Looper.myLooper() == null)
                    Looper.prepare();
                String str = response.body().string();
                if (response.code() != 200 || str.equals("")) {
                    Toast.makeText(MainActivity.this, "请登录", Toast.LENGTH_SHORT).show();
                    return;
                }
                List<Report> reports = JSON.parseArray(str, Report.class);
                userViewModel.setReports(reports);
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //创建fragment
                        if (flag == LIST_FRAGMENT) {
                            ListFragment listFragment = new ListFragment();
                            fragmentManager.beginTransaction().replace(R.id.fragment, listFragment).commitAllowingStateLoss();
                        } else if (flag == ME_FRAGMENT) {
                            MeFragment meFragment = new MeFragment();
                            fragmentManager.beginTransaction().replace(R.id.fragment, meFragment).commitAllowingStateLoss();
                        }

                    }
                });
                Looper.loop();
            }
        });
    }


    /**
     * 从文件中读取数据
     *
     * @return 读取到的数据
     */
    private String[] dataLoad() {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder builder = new StringBuilder();
        try {
            in = this.openFileInput("loginData");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String[] dataList = builder.toString().split(" ");
        return dataList;
    }
}